package com.jinlejia.erp.ui.mine;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.bumptech.glide.Glide;
import com.jinlejia.erp.R;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.databinding.FragmentPersonalCenterBinding;
import com.jinlejia.erp.ui.common.GuideDialog;
import com.jinlejia.erp.ui.common.ProgressDialog;
import com.jinlejia.erp.ui.common.SettingActivity;
import com.jinlejia.erp.ui.mine.actual.ActualSurveyActivity;
import com.jinlejia.erp.ui.mine.assist.AssistAignatureActivity;
import com.jinlejia.erp.ui.mine.calculator.CalculatorActivity;
import com.jinlejia.erp.ui.mine.client.ClientListActivity;
import com.jinlejia.erp.ui.mine.contract.AuditLoginActivity;
import com.jinlejia.erp.ui.mine.contract.MyContractActivity;
import com.jinlejia.erp.ui.mine.contract.MyIntoActivity;
import com.jinlejia.erp.ui.mine.contract.MyRecordingActivity;
import com.jinlejia.erp.ui.mine.key.MyKeyActivity;
import com.jinlejia.erp.ui.mine.myinfo.MyInfoActivity;
import com.jinlejia.erp.ui.mine.process.MyProcessActivity;
import com.jinlejia.erp.ui.mine.pushmoney.PushMoneyActivity;
import com.jinlejia.erp.ui.mine.sign.SignInActivity;
import com.jinlejia.erp.ui.mine.transfer.MyTransferActivity;
import com.jinlejia.erp.utils.ACache;
import com.jinlejia.erp.utils.DataFilter;
import com.jinlejia.erp.utils.SharePTool;
import com.zhy.http.okhttp.OkHttpUtils;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 个人中心（Fragment）
 */

public class PersonalFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {


    private View view;
    // 头像
    public String Icon;
    private JSONObject object;
    ProgressDialog progressDialog;
    //可签到门店
    private ArrayList<Map<String, String>> list = new ArrayList<>();
    private FragmentPersonalCenterBinding binding;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_personal_center, null);
            binding = DataBindingUtil.bind(view);
            binding.setEvent(this);
            EventBus.getDefault().register(this);
            binding.refreshLayout.setColorSchemeResources(R.color.yellow, R.color.light_yellow);
            binding.refreshLayout.setOnRefreshListener(this);
            progressDialog = new ProgressDialog(getActivity(), "请稍后...");
        }
        // 缓存的rootView需要判断是否已经被加过parent，
        // 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
        ViewGroup parent = (ViewGroup) view.getParent();
        if (parent != null) {
            parent.removeView(view);
        }
        getData();
        binding = DataBindingUtil.bind(view);
        binding.setEvent(this);
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        getData();
        if (TextUtils.isEmpty(ACache.get(getActivity()).getAsString("sign_in_guide")))
            new GuideDialog(getContext(), "sign_in_guide", R.mipmap.guide_sign_in).show();
    }


    public void onClick(View view) {
        Intent mIntent = null;
        switch (view.getId()) {
            case R.id.personal_sign_in://签到
                EventBus.getDefault().postSticky(list, "TAG_SIGNIN_DATA");
                mIntent = new Intent(getActivity(), SignInActivity.class);
                break;
            case R.id.personal_head_layout://个人信息
                mIntent = new Intent(getActivity(), MyInfoActivity.class);
                break;
            case R.id.personal_my_compact://我的合同
                mIntent = new Intent(getActivity(), MyContractActivity.class);
                break;
            case R.id.personal_my_into://我的分成
                mIntent = new Intent(getActivity(), MyIntoActivity.class);
                break;
            case R.id.personal_my_solid://我的实勘
                mIntent = new Intent(getActivity(), ActualSurveyActivity.class);
                break;
            case R.id.personal_my_process://我的办件流程
                mIntent = new Intent(getActivity(), MyProcessActivity.class);
                break;
            case R.id.personal_my_key://我的钥匙
                mIntent = new Intent(getActivity(), MyKeyActivity.class);
                break;
            case R.id.personal_my_ticheng://我的提成
                mIntent = new Intent(getActivity(), PushMoneyActivity.class);
                break;
            case R.id.personal_my_xiezhu://我的协助签单
                mIntent = new Intent(getActivity(), AssistAignatureActivity.class);
                break;
            case R.id.personal_my_yidong://我的异动
                mIntent = new Intent(getActivity(), MyTransferActivity.class);
                break;
            case R.id.personal_calculator://房贷计算器
                mIntent = new Intent(getActivity(), CalculatorActivity.class);
                break;
            case R.id.personal_contact_list://通讯录
                mIntent = new Intent(getActivity(), ClientListActivity.class);
                break;
            case R.id.personal_setting://设置
                mIntent = new Intent(getActivity(), SettingActivity.class);
                break;
            case R.id.personal_my_recording://我的录音
                mIntent = new Intent(getActivity(), MyRecordingActivity.class);
                break;
            case R.id.tvLoginCheck://审核登录
                mIntent = new Intent(getActivity(), AuditLoginActivity.class);
                break;
            default:
                break;
        }
        if (mIntent != null)
            startActivity(mIntent);
    }

    /**
     * 获取数据
     */
    public void getData() {
        progressDialog.show();
        OkHttpUtils
                .get()
                .url(ApiConfig.PERSONAL_INFO)
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        if (null != progressDialog && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (null != progressDialog && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        if (DataFilter.filter(getActivity(), response, null)) {
                            object = JSON.parseObject(response.get("data").toString());

                            if (!TextUtils.isEmpty(object.get("imageUrl").toString())) {
                                Icon = ApiConfig.HEADER_URL().concat(object.get("imageUrl").toString());
                                Glide.with(getActivity()).load(Icon).placeholder(R.mipmap.ic_role_head).into(binding.personalRoundimage);
                            } else {
                                binding.personalRoundimage.setImageResource(R.mipmap.ic_role_head);
                            }

                            binding.personalName.setText(object.getString("name"));
                            binding.personalAddress.setText(object.getString("deptName"));

                            //region 保存用户信息
                            JSONObject json = object;
                            String imageUrl = String.valueOf(json.get("imageUrl"));
                            String userName = json.getString("name");
                            String telNum = json.getString("tel");
                            String titleLevel = json.getString("titleLevel");
                            String email = json.getString("email");
                            String deptName = json.getString("deptName");
                            String shareStoreName = json.getString("shareStoreName");


                            SharePTool.UserInfoBean bean = new SharePTool.UserInfoBean();
                            bean.setImageUrl(imageUrl);
                            bean.setEmail(email);
                            bean.setTelNum(telNum);
                            bean.setTitleLevel(titleLevel);
                            bean.setDeptName(deptName);
                            bean.setUserName(userName);
                            bean.setShareStoreName(shareStoreName);
                            SharePTool.saveUserInfoBean(getContext(), bean);
                            //endregion
                            list = JSON.parseObject(object.getJSONArray("coordinateList").toString(), new TypeReference<ArrayList<Map<String, String>>>() {
                            });

                        }
                        if (binding.refreshLayout.isRefreshing()) {
                            binding.refreshLayout.setRefreshing(false);
                        }
                    }
                });
    }


    @Override
    public void onRefresh() {
        getData();
    }

    @Subscriber(tag = "IMG_UPLOAD_HEADER")
    public void Updata(String s) {
        getData();
    }

    @Override
    public void onDestroy() {
        if (null != progressDialog && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    //判断有没有安装微信
    public static boolean isWeixinAvilible(Context context) {
        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mm")) {
                    return true;
                }
            }
        }
        return false;
    }
}
